How to Use Error Boundaries to Handle Errors

Error Boundaries are essential for building stable React applications by catching and managing unexpected errors.


1. Define an ErrorBoundary class component

class ErrorBoundary extends React.Component {
    // initiate component
}

2. State Initialization in Constructor

The constructor initializes the component's state with hasError: false, indicating that, by default, no error has occurred.

constructor(props) {
    super(props);
    this.state = { hasError: false };
}

3. Static Method getDerivedStateFromError

This static method is called by React whenever a child component throws an error. It updates the component’s state to hasError: true, signaling that an error has been caught.

Setting hasError to true triggers a re-render, allowing us to show a fallback UI.

static getDerivedStateFromError() {
    return { hasError: true };
}

4. Render the state

render() {
    if (this.state.hasError) {
        return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
}

In the render method, a check is made on this.state.hasError.

If an error is detected (hasError is true), the component displays a fallback UI with the message “Something went wrong.

If no error is detected, it renders the component’s children (i.e., the components wrapped by ErrorBoundary).

5. Usage

<ErrorBoundary>
    <MyComponent />
</ErrorBoundary>

With this setup, if MyComponent or any of its children throw an error, the ErrorBoundary will catch it and display the fallback UI.

You Might Also Like

Labels: Names used to label loops and control flow

``` outerLoop: for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (j === 1) {...

Custom Hook : Simplify Code with Reusable Logic

Setting up a reusable data-fetching function to simplify API calls and state management. # State In...